package cn.majingjing.core.tool;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @version 6.0
 * @Describe:
 * @Package: com.cntaiping.life.ecustomerservice.admin.util.PropertiesUtils.java
 * @DevTool: Created By Eclipse 4.3
 * @author: Administrator - JingjingMa
 * @Email: <a href="majinding888@163.com">majinding888@163.com</a>
 * @date: 2014-12-3 下午2:43:13
 */
public class SysPropertiesUtils {

    private static String DEFAULT_CONFIG = "/sysconfig.properties";
    private static Properties prop = null;

    static {
        System.out.println("。。。系统属性开始加载中。。。");
    }

    /**
     * 获取属性值
     *
     * @param key
     * @return
     */
    public static String getProp(String key) {
        if (Tools.isNull(prop)) {
            load(DEFAULT_CONFIG);
        }
        return prop.getProperty(key);
    }

    /**
     * 设置或重置属性值
     *
     * @param key
     * @param value
     */
    public static void setProp(String key, String value) {
        if (Tools.isNull(prop)) {
            load(DEFAULT_CONFIG);
        }
        prop.setProperty(key, value);
    }

    /**
     * 加载配置文件,相对于class的路径,以/开头
     *
     * @param cpath
     */
    public static void load(String cpath) {
        InputStream in = null;
        try {
            in = SysPropertiesUtils.class.getResourceAsStream(cpath);
            if (Tools.isNotNull(in)) {
                load(in);
            }
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
            }
        }
    }

    /**
     * 加载配置文件以流的方式
     * @param ins
     */
    public static void load(InputStream ins) {
        try {
            if (Tools.isNull(prop)) {
                prop = new Properties();
            }
            prop.load(ins);
        } catch (IOException e) {
        }
    }

    /**
     * 获取处理后的prop
     *
     * @return
     */
    public static Properties getp() {
        if (Tools.isNull(prop)) {
            load(DEFAULT_CONFIG);
        }
        prop.stringPropertyNames().forEach(t -> {
            String v = SysPropertiesUtils.getProp(t);
            SysPropertiesUtils.setProp(t, v);
        });
        return prop;
    }

}
